<?php
class CronAction extends Action {

	//任务计划
	public function run() {
        // 锁定自动执行
		$lockfile	 =	 RUNTIME_PATH.'cron.lock';
        if(is_writable($lockfile) && filemtime($lockfile) > $_SERVER['REQUEST_TIME'] - 60) {
            return ;
        } else {
            touch($lockfile);
        }

        //set_time_limit(0);
        //ignore_user_abort(true);

		//执行计划任务
		$result	=	$this->sendEmail(5);
		//dump($result);

		// 解除锁定
        unlink($lockfile);
		return ;
    }

    //设置发送邮件每次发送5条
	public function sendEmail($count=5){
		$invite	=	D('Invite');
		$email_arr	=	$invite->where('status=0')->limit($count)->findAll();

		if(is_array($email_arr) && count($email_arr)>0){
			$opts = $this->opts;
			$option['email_sendtype']			=	$opts['email_sendtype'];
			$option['email_ssl']				=	$opts['email_ssl'];
			$option['email_smtp']				=	$opts['email_smtp'];
			$option['email_port']				=	$opts['email_port'];
			$option['email_account']			=	$opts['email_address'];
			$option['email_password']			=	$opts['email_password'];
			$option['email_sender']				=	$opts['site_name'];
			$option['email_sender_account']		=	$opts['email_address'];
			$option['email_apply_account']		=	$opts['email_address'];

			foreach($email_arr as $k=>$v){

				$option['email_sender']				=	$v['username'];
				if($v['senderemail']){
					$option['email_sender_account']		=	$v['senderemail'];
					$option['email_apply_account']		=	$v['senderemail'];
				}
				if(is_email($v['toemail'])){
					$sr	=	send_email($v['toemail'],$v['title'],$v['content'],$option);
					if($sr) {
						$ret[] = D('Invite')->setField('status',1,'id='.$v['id']);
					}else{
						$ret[] = D('Invite')->setField('status',-1,'id='.$v['id']);
					}
				}else{
					D('Invite')->delete($v['id']);
				}
			}
		}

		return $ret;
	}
}
?>